﻿using System.Web.Mvc;
using AmorCanino.Web.Models.Authentication;
using AmorCanino.Web.Models.Models;
using AmorCanino.Web.Models.Services;
using System.Web.Security;
using AmorCanino.Exceptions;
using System;

namespace AmorCanino.Web.Controllers
{
    public class AccountController : Controller
    {
        private IUserService userService;

        public AccountController()
        {
            userService = new UserService();
        }

        public AccountController(IUserService service)
        {
            userService = service;
        }

        [Authorize()]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize()]
        public ActionResult Messages()
        {
            var userId = AuthUser.Current().id;
            return View(new MessagingService().GetAllMessages(userId));
        }

        [Authorize(Roles="Admin")]
        public ActionResult Products()
        {
            return View();
        }

        [Authorize()]
        public ActionResult MyPets()
        {
            return View();
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var currentUser = userService.getUserByCredentials(model.Email, model.Password);

                if (currentUser != null)
                {
                    AuthUser.SetAuthUser(currentUser.id, currentUser.Email, false);

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return View(model);
        }

        public ActionResult LogOut()
        {
            AuthUser.LogoutUser();
            return Redirect(HttpContext.Request.UrlReferrer.ToString());
        }

        public ActionResult Register(UserRegistrationModel model)
        {
            return View(model);
        }

        [HttpPost]
        public ActionResult Register(UserRegistrationModel model, string repeatedPassword)
        {
            if (ModelState.IsValid)
            {
                if (model.Password.Equals(repeatedPassword))
                {
                    try
                    {
                        var newUser = new UserService().CreateUser(model);
                        AuthUser.SetAuthUser(newUser.id, newUser.Email, false);
                        return RedirectToAction("Index", "Home");
                    }
                    catch (BusinessRuleException)
                    {
                        return RedirectToAction("index", "home");
                    }
                }
                else
                    ViewBag.PasswordError = "Las contraseñas deben ser iguales";
            }
            return View(model);
        }

        #region Messages
        [HttpPost, Authorize()]
        public JsonResult RequestMessage(int originId, int targetId)
        {
            var userId = AuthUser.Current().id;
            return new JsonResult() { Data = new MessagingService().GetMessage(originId, targetId, userId).Messages };
        }

        [HttpPost, Authorize()]
        public JsonResult PostMessage(int originId, int targetId, string message)
        {
            var userId = AuthUser.Current().id;
            new MessagingService().SetMessages(new Communication()
            {
                Message = message,
                PublishedDate = DateTime.UtcNow,
                UserId = userId.ToString()
            }, originId, targetId);
            return new JsonResult() { Data = "ok" };
        }
        #endregion
    }
}